import { Settings as GatewaySettings } from "maishu-node-auth/gateway";
import { Settings as PermissionSettings } from "maishu-node-auth/permission";
import { Settings as PortalSettings } from "maishu-node-auth/portal";
import { start as startNodeAuth, roleIds } from "maishu-node-auth";
import { start as startImage, Settings as ImageSettings } from "maishu-image-service";
import { start as startMerchant, merchantRoleId } from "./merchant";
import { start as startShop, Settings as ShopSettings } from "./shop";
import { start as startWeiXin } from "./weixin";
import { start as startmember } from "./member";
import { start as startAccount } from "./account";

import path = require("path");
import fs = require("fs");
import { LogLevel } from "maishu-node-mvc";

export interface Settings {
    logLevel?: LogLevel,
    db_host: string,
    db_port: number,
    db_user: string,
    db_password: string,
    target_host: string,            // 目标主机，服务所在的主机
    gatewayPort: number,
    gatewayBindIP: string,
}

export function start(config: Settings) {

    const gatewayPort = config.gatewayPort;
    const gatewayBindIP = config.gatewayBindIP;
    const gateway = gatewayBindIP ? `${gatewayBindIP}:${gatewayPort}` : `127.0.0.1:${gatewayPort}`;

    const permissionStationPort = gatewayPort + 100;
    const portalStationPort = gatewayPort + 200;
    const merchantStationPort = gatewayPort + 300;
    const shopStationPort = gatewayPort + 400;
    const imageStationPort = gatewayPort + 500;
    const weixinStationPort = gatewayPort + 600;
    const memberStationPort = gatewayPort + 700;
    const accountStationPort = gatewayPort + 800;
    const imageStation = config.gatewayBindIP ? `${gatewayBindIP}:${imageStationPort}` : `127.0.0.1:${imageStationPort}`;

    //===========================================
    let gatewayStationSettings: GatewaySettings = {
        port: gatewayPort,
        bindIP: gatewayBindIP,
        db: {
            user: config.db_user,
            password: config.db_password,
            database: "node_auth_gateway",
            host: config.db_host,
            port: config.db_port,
            charset: "utf8",
        },
        logLevel: "all",
        virtualPaths: {
            node_modules: path.join(__dirname, "node_modules"),
        },
        proxy: {
            '/AdminSite/(\\S+)': `http://${config.target_host}:9000/Admin/$1`,
            '/AdminStock/(\\S+)': `http://${config.target_host}:9005/Admin/$1`,
            '/AdminShop/(\\S+)': `http://${config.target_host}:9010/Admin/$1`,
            '/AdminMember/(\\S+)': `http://${config.target_host}:9020/Admin/$1`,
            '/AdminWeiXin/(\\S+)': `http://${config.target_host}:9030/Admin/$1`,
            '/AdminAccount/(\\S+)': `http://${config.target_host}:9035/Admin/$1`,
            '/UserSite/(\\S+)': `http://${config.target_host}:9000/User/$1`,
            '/UserStock/(\\S+)': `http://${config.target_host}:9005/User/$1`,
            '/UserShop/(\\S+)': `http://${config.target_host}:9010/User/$1`,
            '/UserMember/(\\S+)': `http://${config.target_host}:9020/User/$1`,
            '/UserWeiXin/(\\S+)': `http://${config.target_host}:9030/User/$1`,
            '/UserAccount/(\\S+)': `http://${config.target_host}:9035/User/$1`,
            "^/Images/Editor/(\\S+)": "http://web.alinq.cn/store2/Images/Editor/$1",
            "^/image/(\\S+)": `http://${imageStation}/$1`,
        },
        headers: {
            'Content-Type': 'application/json;charset=utf-8',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': '*',
            'Access-Control-Allow-Headers': '*'
        },
        permissions: {
            "/": { roleIds: [roleIds.anonymous] },
            // "/socket.io/*": { roleIds: [roleIds.anonymousRoleId] },
            // "/socket*": { roleIds: [roleIds.anonymousRoleId] },
            "*.js": { roleIds: [roleIds.anonymous] },
            "*.html": { roleIds: [roleIds.anonymous] },
            "*.css": { roleIds: [roleIds.anonymous] },
            "*.less": { roleIds: [roleIds.anonymous] },
            "*.jpg": { roleIds: [roleIds.anonymous] },
            "*.png": { roleIds: [roleIds.anonymous] },
            "*.woff": { roleIds: [roleIds.anonymous] },
            "*.map": { roleIds: [roleIds.anonymous] },

            "/favicon.ico": { roleIds: [roleIds.anonymous] },
            "/auth/user/login": { roleIds: [roleIds.anonymous] },
            "/auth/station/list": { roleIds: [roleIds.anonymous] },
            "/auth/station/register": { roleIds: [roleIds.anonymous] },

            "/AdminMember/*": { roleIds: [merchantRoleId] },
            "/AdminShop/*": { roleIds: [merchantRoleId] },
            "/AdminStock/*": { roleIds: [merchantRoleId] },
            "/AdminAccount/*": { roleIds: [merchantRoleId] },
            "/AdminWeiXin/*": { roleIds: [merchantRoleId] },
            "/UserMember/*": { roleIds: [merchantRoleId, roleIds.normalUser] },
            "/UserShop/*": { roleIds: [merchantRoleId, roleIds.normalUser] },
            "/UserStock/*": { roleIds: [merchantRoleId, roleIds.normalUser] },
            "/Images/Editor/*": { roleIds: [roleIds.anonymous] },
            "/portal/*": { roleIds: [roleIds.anonymous] },
            "/image/*": { roleIds: [roleIds.anonymous] },
            "/*/websiteConfig": { roleIds: [roleIds.anonymous] },
            "/*/clientFiles": { roleIds: [roleIds.anonymous] }
        },

    }
    // permissions[`${stationPath}websiteConfig`] = { roleIds: [roleIds.anonymous] };
    // permissions[`${stationPath}clientFiles`] = { roleIds: [roleIds.anonymous] };
    let permissionStationSettings: PermissionSettings = {
        port: permissionStationPort,
        gateway,
        db: {
            user: config.db_user,
            password: config.db_password,
            database: "node_auth_permission",
            host: config.db_host,
            port: config.db_port,
            charset: "utf8",
        },
        virtualPaths: {
            "node_modules": path.join(__dirname, "node_modules")
        }
    }

    let portalStationSettings: PortalSettings = {
        port: portalStationPort, gateway,
        indexPage: `merchant:index`,
    }

    let shopSettings: ShopSettings = {
        port: shopStationPort,
        db: {
            host: config.db_host,
            port: config.db_port,
            user: config.db_user,
            password: config.db_password,
            database: "shop_shop",
            charset: "utf8",
        }, gateway,
    }

    let imageSettings: ImageSettings = {
        port: imageStationPort,
        db: {
            host: config.db_host,
            database: "shop_image",
            port: config.db_port,
            user: config.db_user,
            password: config.db_password,
        }
    };

    startNodeAuth({
        gatewaySettings: gatewayStationSettings,
        permissionSettings: permissionStationSettings,
        portalSettings: portalStationSettings,
    }).then(() => {
        startShop(shopSettings);
        startImage(imageSettings);
        setTimeout(() => {
            startMerchant({
                gateway: gateway,
                port: merchantStationPort,
                permissionDB: permissionStationSettings.db,
                gatewayDB: gatewayStationSettings.db,
                logLevel: config.logLevel
            });
        }, 1000);
        startWeiXin({
            port: weixinStationPort,
            gateway: gateway,
            db: {
                host: config.db_host,
                database: "shop_weixin",
                port: config.db_port,
                user: config.db_user,
                password: config.db_password,
                charset: "utf8"
            }
        });
        startmember({
            port: memberStationPort,
            gateway: gateway,
            db: {
                host: config.db_host,
                database: "shop_member",
                port: config.db_port,
                user: config.db_user,
                password: config.db_password,
                charset: "utf8"
            }
        })
        startAccount({
            port: accountStationPort,
            gateway
        })
    })
}

process.on("uncaughtException", function (err) {
    console.error('An uncaught error occurred!');
    console.error(err.stack)
})